const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const session = require('express-session')
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const { pool } = require('./db/index');
const passport = require('passport');
const flash = require('connect-flash');

const MySQLStore = require('express-mysql-session')(session);

const app = express();

const sessionStore = new MySQLStore({}, pool);

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
  name: 'sessionId', // 指定存储在 cookie 中的 session ID 的 key 名称
  secret: 'keyboard cat',
  resave: false, // don't save session if unmodified
  saveUninitialized: false, // don't create session until something stored
  store: sessionStore,
  cookie: {
    maxAge: 24 * 60 * 60 * 1000,// 有效期（毫秒）
    httpOnly: true,    // 防止客户端脚本读取 Cookie
  }
}));

app.use(passport.initialize());
app.use(passport.session());  // 仅通过会话恢复用户身份
app.use(flash())

// 可以代替 app.use(passport.session());
// app.use(passport.authenticate('session'));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  // console.log('error-handler:', err);
  res.locals.env = 'test';
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
